<template>
 <div class="customergroupindex">
   <Row class="nav">
      <Col span="8">
        <Button type="primary" @click="Goaddcustomergroup">+新建客户分组</Button>
        <Button type="primary" @click="GocustomerLead">+导入文件创建分组</Button>
      </Col>
      <Col span="12" push="10">
        <Row>
          <Col span="2" pull="3">
            <Input type="text" class="search"  placeholder="请输入搜索内容" style="width:150px;" v-model="search_content" clearable/>
          </Col>
          <Col span="2" push="1" >
            <Button type="primary"  icon="ios-search" class="button_search" @click.native="customerTargetTableList" :disabled="queryDisabled" ></Button>
          </Col>
        </Row>
      </Col>
   </Row>
   <div class="tabs_container">
    <Row>
        <Col span="20">
            <div class="tabs_box">
                <Row>
                    <ul class="tabs_list" style="width:70vw;overflow-x:scroll;">
                        <li v-for="(tab, index) in tabs" :class="{active: index==num}" @click="toggle(index,tab)" :key="index">
                           <span :class="{active: index==num}">
                                    {{tab.name}}
                           </span>
                        <Dropdown trigger="click" @mouseover="toggle(index)">
                          <Icon type="ios-arrow-down"></Icon>
                          <DropdownMenu slot="list">
                            <DropdownItem @click.native="modal6=true">编辑</DropdownItem>
                            <DropdownItem @click.native="modal7=true">删除</DropdownItem>
                          </DropdownMenu>
                        </Dropdown>
                        </li>
                    <div class="clear"></div>
                    </ul>
                    <div class="clear"></div>
                </Row>
            </div>
        </Col>
        <Col span="2" push="2" style="padding-top:1vh;">
          <Button @click="modal1 = true" size="small" class="add_btn">+新建分类</Button>
        </Col>
    </Row>
    <Row>
        <Col span="24">
             <div class="content">
                <div class="box" v-for="(value, index) in tabContents" v-show="index == num"  :key="index">
                    <Table :loading="TableLoading" border :columns="columns7" :data="data6"></Table>
                </div>
            </div>
        </Col>
    </Row>
    <Row type="flex" justify="center" style="margin-top:15px;">
        <Col>
           <Page :id="pageId" show-total :total="total" :page-size="pageSize" @on-change="pageable" @on-page-size-change="pagesizeable" show-sizer show-elevator></Page>
        </Col>
        <Col push="1">
          <div>
            <Button style="margin-top: 6px;" type="primary" size="small" @click="goElevatorPage(pageId)">跳转</Button>
          </div>
        </Col>
    </Row>

   </div>
   <Modal
        v-model="modal1"
        title="新建分类">
        <Form ref="formValidate1" :model="formValidate1" :rules="ruleValidates1" :label-width="80">
          <FormItem label="分类名称:" prop="name">
              <Input v-model="formValidate1.name" placeholder="请输入分类名称" style="width:90%;" clearable></Input>
          </FormItem>
        </Form>
         <div slot="footer">
           <Button size="large" type="primary" @click="addItem('formValidate1')">保存</Button>
         </div>
    </Modal>
    <Modal
        v-model="modal2"
        title="提示信息"
        @on-ok="remove"
        >
        <h3>确定删除该分组？</h3>
    </Modal>
    <Modal
        v-model="modal3"
        title="复制分组"
        >
         <Form ref="formValidate2" :model="formValidate2" :rules="ruleValidates2" :label-width="100">
          <FormItem label="人群名称:" prop="copygroupname">
              <Input v-model="formValidate2.copygroupname" placeholder="请输入分类名称" style="width:200px;" clearable></Input>
          </FormItem>
          <FormItem label="选择人群分类:"  style="margin-top:4vh;" :label-width="100">
             <Select v-model="formValidate2.grouptype" placeholder="请选择..." style="width:200px;"  clearable>
               <Option
                 v-for="item in noRecycelTabs"
                 :value="item.id"
                 :key="item.name"
               >{{ item.name }}</Option>
            </Select>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button size="large" type="primary" @click="copyGroup('formValidate2')">确定</Button>
        </div>
    </Modal>
    <Modal
        v-model="modal10"
        title="移动分组"
        >
         <Form ref="formValidate3" :model="formValidate3" :label-width="100">
          <FormItem label="选择人群分类:" style="margin-top:4vh;" :label-width="100">
             <Select v-model="formValidate3.movegroup" placeholder="请选择..." style="width:200px;"  clearable>
               <Option
                 v-for="item in noRecycelTabs"
                 :value="item.id"
                 :key="item.name"
               >{{ item.name }}</Option>
            </Select>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button size="large" type="primary" @click="moveGroup('formValidate3')">确定</Button>
        </div>
    </Modal>
    <Modal
        v-model="modal6"
        title="修改分类"
        >
        <Form ref="formValidate4" :model="formValidate4" :rules="ruleValidates4" :label-width="80">
          <FormItem label="分类名称:" prop="edittabsnameInput">
              <Input v-model="formValidate4.edittabsnameInput" clearable placeholder="请输入分类名称" style="width:90%;"></Input>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button size="large" type="primary" @click="editItem(num, 'formValidate4')">保存</Button>
        </div>
    </Modal>
    <Modal
        v-model="modal7"
        title="提示信息"
        @on-ok="handleTabRemove(num)"
        >
        <h3>确定删除该分类吗？</h3>
    </Modal>

 </div>
</template>
<script>
  import {  customerTargetTableList,
            targetCategoryTableList ,
            addTargetCategory,
            editTargetCategory,
            delTargetCategory,
            copyTargetGroup,
            moveTargetGroup,
            delTargetGroup,
            targetSum
          } from '@/api/customer'
export default {
  name:'CustomerGroupIndex',
  data () {
    const validateNameLength = (rule, value, callback) => {
      if (value.length > 8 ) {
        callback(new Error("长度过长，最多八个字！"));
      } else {
        callback();
      }
    };

      return {
        delFlag: 0,
        TableLoading:false,
        queryDisabled: false,
        modal1: false,
        modal2: false,
        modal3: false,
        modal10: false,
        modal5: false,
        modal6: false,
        modal7: false,
        modalparam:"",
        pageNum: 1,
        pageSize: 10,
        total: 0,
        search_content:'',
        tabs:[],
        noRecycelTabs:[],
        tabContents: [],
        num: 0,
        tabContent:"",
        formValidate1:{
          name:''
        },
        formValidate2:{
          copygroupname: '',
          grouptype: ''
        },
        formValidate3:{
          movegroup: ''
        },
        formValidate4:{
          edittabsnameInput: ''
        },
        formValidate:{
          name:''
        },
        ruleValidates1: {
          name: [
            {required: true, message: '分类名称不能为空!', trigger: 'blur'},
            { validator: validateNameLength, message:"长度过长，最多八个字！", trigger: 'change'}
          ]
        },
        ruleValidates2: {
          copygroupname: [
            { required: true, message: '分组名称不能为空!', trigger: 'blur' }
          ],
          /*grouptype: [
            {  message: '分类不能为空!', trigger: 'change' }
          ]*/
        },
        ruleValidates3: {
          /*movegroup: [
            { message: '分类不能为空!', trigger: 'change'}
          ]*/
        },
        ruleValidates4: {
          edittabsnameInput: [
            {required: true, message: '分类不能为空!', trigger: 'blur'},
            { validator: validateNameLength, message:"长度过长，最多八个字！", trigger: 'change'}
          ]
        },
        columns7: [
            {
                title: '分组名称',
                key: 'name',
                align:'center',
                width: 100,
            },
            {
                title: '分组类型',
                key: 'typeName',
                align:'center',
                width: 100,
            },
            {
              title: '固定人群类型',
              key: 'isFixedTarget',
              align:'center',
              width: 150,
              render: (h, params) => {
                let text = "-";
                if (params.row.isFixedTarget == 0) {
                  text = "动态分组";
                } else if (params.row.isFixedTarget == 1) {
                  text = "静态分组";
                }
                return h(
                  "span",{},text
                );
              }
            },
            {
                title: '人群总数',
                key: 'lastCalcTargetNum',
                width: 150,
                align:'center'
            },
            {
                title: '创建时间',
                key: 'createDate',
                width: 150,
                align:'center',
                render: (h, params) => {
                return h('div', this.changeDate(this.data6[params.index].createDate));
              }
            },
            {
                title: '创建人',
                key: 'createBy',
                width: 100,
                align:'center'
            },
            {
            title: '操作',
            key: 'action',
            width: 450,
            align: 'center',
            render: (h, params) => {
                return h('div', [
                    h('Button', {
                        props: {
                            type: 'primary',
                            size: 'small'
                        },
                        style: {
                            marginRight: '5px'
                        },
                        on: {
                            click: () => {
                                this.Skip(params.row.id)
                            }
                        }
                    }, '查看客户'),
                    h('Button', {
                        props: {
                            type: 'error',
                            size: 'small'
                        },
                        style: {
                            marginRight: '5px'
                        },
                        on: {
                            click: () => {
                              this.editorTarget(params.row.id)
                            }
                        }
                    }, '编辑'),
                    h('Button', {
                        props: {
                            type: 'warning',
                            size: 'small'
                        },
                        style: {
                            marginRight: '5px'
                        },
                        on: {
                            click: () => {
                              this.showmodal3(params);
                            }
                        }
                    }, '复制'),
                    h('Button', {
                        props: {
                            type: 'error',
                            size: 'small'
                        },
                        style: {
                            marginRight: '5px'
                        },
                        on: {
                            click: () => {
                                    this.showmodal2(params);
                            }
                        }
                    }, '删除'),
                    h('Button', {
                        props: {
                            type: 'success',
                            size: 'small'
                        },
                        style: {
                            marginRight: '5px',
                        },
                        on: {
                            click: () => {
                              this.targetSum(params);
                            }
                        }
                    }, '计算'),
                    h('Button', {
                        props: {
                            type: 'info',
                            size: 'small'
                        },
                        style: {
                            marginRight: '5px'
                        },
                        on: {
                            click: () => {
                                    this.showmodal10(params);
                            }
                        }
                    }, '移动')
                ]);
            }
        }
        ],
        data6: [],
        pageId: 'targetPage'
      }
  },
  methods:{
    //点击跳转到输入的页码
    goElevatorPage(pageId){
      var evtObj;
      var thisPage=document.getElementById(pageId);
      var elevatorDiv=thisPage.getElementsByClassName("ivu-page-options-elevator");
      if(elevatorDiv && elevatorDiv.length>0){
        var pageInput = elevatorDiv[0].getElementsByTagName("input")[0];
        if (window.KeyEvent) {//firefox 浏览器下模拟事件
          evtObj = document.createEvent('KeyEvents');
          evtObj.initKeyEvent("keyup", true, true, window, true, false, false, false, 13, 0);
        } else {//chrome 浏览器下模拟事件
          evtObj = document.createEvent('UIEvents');
          evtObj.initUIEvent("keyup", true, true, window, 1);
          delete evtObj.keyCode;
          if (typeof evtObj.keyCode === "undefined") {//为了模拟keycode
            Object.defineProperty(evtObj, "keyCode", { value: 13 });
          } else {
            evtObj.key = String.fromCharCode(13);
          }
        }
        pageInput.dispatchEvent(evtObj);
      }
    },
    ruleValidate(){
      if(this.search_content==""){
         this.$Notice.warning({
           title: " 提示信息",
           desc: "搜索内容不能为空!"
        });
      }
    },
    copyGroup(name){
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true;
          var reqParams = {
            targetId:this.modalparam.row.id,
            newTargetName:this.formValidate2.copygroupname,
            toTargetCategoryId:this.formValidate2.grouptype,
          };
          copyTargetGroup(reqParams).then(res => {
            if (res.data.code == 200) {
              this.$Message.success("复制成功!");
              this.targetCategoryId = this.tabs[0].id;
              this.targetCategoryTableList();
              this.modal3 = false;
              this.loading = false;
            }else {
              this.$Message.error("复制失败!"+error);
              this.loading = false;
            }
          }).catch(error => {
            this.$Message.error(error);
            this.loading = false;
          });
        }
      })
    },
    moveGroup(name){
      this.loading = true;
      var reqParams = {
        targetId:this.modalparam.row.id,
        toTargetCategoryId:this.formValidate3.movegroup,
      }
      moveTargetGroup(reqParams).then(res => {
        if (res.data.code == 200) {
          this.$Message.success("移动成功!");
          this.targetCategoryId = this.tabs[0].id;
          this.targetCategoryTableList();
          this.modal10 = false;
          this.loading = false;
        }else {
          this.$Message.error("移动失败!"+error);
          this.loading = false;
        }
      }).catch(error => {
        this.$Message.error(error);
        this.loading = false;
      });
    },
    //时区日期格式转换(TZ)
    changeDate(dateA) {
      var dateee = new Date(dateA).toJSON();
      var date = new Date(+new Date(dateee)+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
      return date;
    },
    editruleValidate(){
      if(this.search_content==""){
         this.$Notice.warning({
           title: " 提示信息",
           desc: "分类名称不能为空!"
        });
      }
    },
    Skip(id){
      this.$router.push({path:'/customer/targetCustomerList/'+id, query:{"_button": true}})
    },
    showmodal2(val){
      this.modal2 = true;
      this.modalparam = val;
    },
    showmodal3(val){
      this.modal3 = true;
      this.modalparam = val;
    },
    //编辑
    editorTarget(params){
      this.$router.push({path: "/customer/addCustomerGroup/"+ params});
    },
    showmodal10(val){
      this.modal10 = true;
      this.modalparam = val;
    },
    showmodal6(index){
      this.modal6 = true;
    },
    showmodal7(index){
      this.modal7 = true;
    },
    remove () {
      this.loading = true;
      delTargetGroup(this.modalparam.row.id).then(res => {
        if (res.data.data) {
          this.$Message.success("删除成功!");
          this.targetCategoryTableList();
          this.modal2 = false;
          this.loading = false;
        }else {
          this.$Message.error("删除失败!"+error);
          this.loading = false;
        }
      }).catch(error => {
        this.$Message.error(error);
        this.loading = false;
      });
    },
    handleTabRemove (num) {
        if(this.num == 0){
            this.$Message.error('不能删除默认分类')
        }else{
          this.loading = true;
          var reqParams = {
            id:this.tabs[num].id,
          }
          delTargetCategory(this.tabs[num].id).then(res => {
            if (res.data.data) {
              this.$Message.success("删除成功!");
              this.num = 0;
              this.targetCategoryId = this.tabs[0].id;
              this.targetCategoryTableList();
              this.modal1 = false;
              this.loading = false;
            }else {
              this.$Message.error("删除失败!"+error);
              this.loading = false;
            }
          }).catch(error => {
            this.$Message.error(error);
            this.loading = false;
          });
        }
    },
    toggle(index,tab){
      this.num = index;
      this.targetCategoryId = tab.id;
      this.formValidate.edittabsnameInput = tab.name;
      this.customerTargetTableList();
    },
    addItem(name){  // 添加分类
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true;
          var reqParams = {
            name:this.formValidate1.name,
          }
          addTargetCategory(reqParams).then(res => {
            if (res.data.data) {
              this.$Message.success("添加成功!");
              this.num = 0;
              this.targetCategoryId = this.tabs[0].id;
              this.targetCategoryTableList();
              this.modal1 = false;
              this.loading = false;
            }else {
              this.$Message.error("添加失败!"+error);
              this.loading = false;
            }
          }).catch(error => {
            this.$Message.error(error);
            this.loading = false;
          });
        }
      })
    },
    editItem(num, name){
      this.$refs[name].validate((valid) => {
          if (valid) {
            this.tabs[num].value = this.formValidate4.edittabsnameInput[num].value;
            this.loading = true;
            var reqParams = {
              id:this.tabs[num].id,
              name:this.formValidate4.edittabsnameInput,
            }
            editTargetCategory(reqParams).then(res => {
              if (res.data.data) {
                this.$Message.success("编辑成功!");
                this.targetCategoryId = this.tabs[num].id;
                this.num = num;
                this.targetCategoryTableList();
                this.modal6 = false;
                this.loading = false;
              }else {
                this.$Message.error("编辑失败!"+error);
                this.loading = false;
              }
            }).catch(error => {
              this.$Message.error(error);
              this.loading = false;
            });
          }
      })

    },
    Goaddcustomergroup(){
      this.$router.push({path:'/customer/addCustomerGroup'})
    },
    GocustomerLead(){
      this.$router.push({path:'/customer/customerLead'})
    },
    // 切换分页
    pageable(current) {
        this.pageNum = current;
         this.customerTargetTableList();
    },
    // 切换每页条数时的回调，返回切换后的每页条数
    pagesizeable(val) {
      this.pageSize = val;
      this.customerTargetTableList();
    },
    //查询人群类别tabs
    targetCategoryTableList(params) {
      var reqParams = {
        page: this.page,
        limit: this.limit,
        total: this.total
      };
      targetCategoryTableList(reqParams).then(res => {
        if (res.data.code == 200) {
          var tabDelete = {
            name:'回收站',
            id: null,
            delFlag: 1
          };
          var tabDefault = [{
            name:'默认分组',
            id: 0,
            delFlag: 0
          }];
          var tabArr = res.data.data;
          this.noRecycelTabs = tabArr;
          this.tabs = tabDefault.concat(tabArr.concat(tabDelete));
          if(this.tabs.length > 0){
            this.targetCategoryId = this.tabs[this.num].id;
            this.customerTargetTableList();
          }
          this.tabContents = (this.tabs);
        }
      })
      .catch(error => {
        this.$Message.error(error);
      });
    },
    // 查询
    customerTargetTableList() {
      this.queryDisabled = true;
      this.TableLoading = true;
      if (this.targetCategoryId == null){
        this.delFlag = 1;
      }else {
        this.delFlag = 0;
      }
      var targetCategoryId = this.targetCategoryId===0?null:this.targetCategoryId;
      var reqParams = {
        page: this.pageNum,
        limit: this.pageSize,
        targetCategoryId: targetCategoryId,
        delFlag: this.delFlag,
        name:this.search_content
      };
      customerTargetTableList(reqParams).then(res=>{
        this.queryDisabled = false;
        this.TableLoading = false;
        if (res.data.code == 200) {
          this.data6 =  res.data.result.records;
          this.pageSize = res.data.result.size;
          this.pageNum = res.data.result.pageNum;
          this.total = res.data.result.total;
        }else {
          this.$Message.error("操作失败【" + error + "】");
        }
      }).catch(error=>{
        this.TableLoading = false;
        this.queryDisabled = false;
        this.$Message.error("操作失败【" + error + "】");
      })

    },

    //计算
    targetSum(param){
      this.loading = true;
      this.data6[param.index].lastCalcTargetNum = '计算中...';
      var req = {
          targetId: param.row.id
      };
      targetSum(req).then(res => {
        if (res.data.code == 200) {
          this.$Message.success("计算成功!");
          this.data6[param.index].lastCalcTargetNum = res.data.data;

          this.loading = false;
        }else {
          this.$Message.error("计算失败!"+error);
          this.loading = false;
        }
      }).catch(error => {
        this.$Message.error(error);
        this.loading = false;
      });
    }
  },
  computed:{
      tablestyle(){
          return {
              marginTop:'-10vh'
          }
      },
  },
  created() {
    this.targetCategoryTableList();
  }
}
</script>
<style lang="scss" scoped>
@import "../../styles/common.scss";
.customergroupindex{
  @include container_global;
 .nav{        // 导航
   width: 85vw;
   height:8vh;
   .button_group_left{
     width: 20vw;
     padding: 10px 0px 0px 0px;
    .button_add{
       padding: 8px;
       color: #fff;
       border: none;
       background: lightskyblue;
       &:hover{
         cursor: pointer;
       }
     }
     .button_file{
       @extend .button_add;
     }
   }
   .button_group_right{
     .search{
        width: 200px;
        margin:-5vh 3vw 0px 0px;
     }
     .button_search{
       float: right;
       margin-top: -5vh;
     }
   }
 }
  .tabs_container{   //tabs
    width:100%;
    padding-bottom: 2vh;
    background-color: #fff;
    .tabs_box{
      width: 100%;
      .tabs_list{
        width:50vw;
        min-height: 6vh;
        border-bottom:1px solid #ccc;
        display: flex;
        flex-wrap: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        li{
          display: block;
          float: left;
          min-width: 13vw;
          height: 5vh;
          font-size: 14px;
          color: #333;
          line-height: 40px;
          text-align: center;
          &:hover{
            cursor: pointer;
          }
          .active{
            //min-width: 9vw;
            color: lightskyblue;
            border-bottom:5px solid lightskyblue;
          }
        }

      }
      .add_btn{
        width:6vw;
        height: 5vh;
        float: right;
        margin-right: 1%;
        margin-top: -8vh;
      }
    }
    .content{
      width: 100%;
      margin-top: 4vh;
    }
  }
}
</style>
